#import "PrivatePhotosViewController.h"
#import "PrivatePhotosModel.h"
#import <HUPhotoBrowser.h>
#import "PrivatePhotosLogic.h"
#import <TZImagePickerController.h>
#import "PrivatePhotosCollectionViewCell.h"
#import "ZKPhotoBrowser.h"
@interface PrivatePhotosViewController ()<PrivatePhotosDelegate,UICollectionViewDelegate,UICollectionViewDataSource,TZImagePickerControllerDelegate>
@property (nonatomic, strong) UIButton *uploadPhotoButton;
@end
@implementation PrivatePhotosViewController
- (void)viewDidLoad {
    self.title = ASLocalizedString(@"相册");
    [super viewDidLoad];
    _logic = [PrivatePhotosLogic new];
    _logic.delegagte = self;
    _logic.touid = self.touid;
    [[HUDHelper sharedInstance] syncLoading];
    [_logic loadData];
    [self setupUI];
}
#pragma mark ————— 初始化页面 —————
-(void)setupUI{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView.collectionViewLayout = layout;
    layout.minimumLineSpacing = 1;
    layout.minimumInteritemSpacing = 1;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.collectionView.backgroundColor = CViewBgColor;
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([PrivatePhotosCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([PrivatePhotosCollectionViewCell class])];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    if([self.touid isEqualToString:curUser.id])
    {
        self.uploadPhotoButton = [[OmBaseButton alloc] initWithImageName:@"OmCamera" mode:UIViewContentModeScaleToFill].fp_addTargetActionForControlEvents(self, @selector(addPhoto), UIControlEventTouchUpInside);
        [self.view addSubview:self.uploadPhotoButton];
        [self.uploadPhotoButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.equalTo(@(RPX(62)));
            make.right.equalTo(self.view).offset(RPX(-18));
            make.bottom.equalTo(self.view).offset(RPX(-18));
        }];
    }
}
-(void)addPhoto
{
    [self selectPhoto];
}
-(void)selectPhoto {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:6 delegate:self];
    [imagePickerVc.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    imagePickerVc.naviBgColor = [UIColor blackColor];
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if(photos.count >0)
        {
            _photoImage = photos;
            [self uplaodImages];
        }
    }];
    imagePickerVc.naviTitleColor = [UIColor blackColor];
    imagePickerVc.barItemTextColor =  [UIColor blackColor];
    imagePickerVc.oKButtonTitleColorNormal = [UIColor blackColor];
    imagePickerVc.showSelectBtn = YES;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
-(void)uplaodImages
{
    NSMutableArray *nameArr = [NSMutableArray array];
    for (int i=0; i<_photoImage.count; i++) {
        [nameArr addObject:[NSString stringWithFormat:@"img%d",i]];
    }
    [[HUDHelper sharedInstance] loading:ASLocalizedString(@"上传私照中..")];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:curUser.id forKey:@"uid"];
    [param setObject:curUser.token forKey:@"token"];
    [PPNetworkHelper uploadImagesWithURL:[cyurl makeURLWithC:@"private_photo_api" A:@"private_photos_upload"] parameters:param name:nil images:_photoImage fileNames:nil imageScale:1 imageType:@"png" progress:^(NSProgress *progress) {
    } success:^(id responseObject) {
        [MBProgressHUD hideHUD];
        if([[responseObject valueForKey:@"code"] intValue] == 1)
        {
            [MBProgressHUD showTopTipMessage:ASLocalizedString(@"上传成功!")];
            [_logic loadData];
        }
        else
        {
            [MBProgressHUD showTipMessageInView:[responseObject valueForKey:@"msg"]];
        }
    } failure:^(NSError *error) {
    }];
}
#pragma mark ————— 下拉刷新 —————
-(void)headerRereshing{
    _logic.page = 0;
    [_logic loadData];
    [self removeNoDataImage];
}
#pragma mark ————— 上拉刷新 —————
-(void)footerRereshing{
    _logic.page+=1;
    [_logic loadData];
    [self removeNoDataImage];
}
#pragma mark ————— 数据拉取完成 渲染页面 —————
-(void)requestDataCompleted{
    [[HUDHelper sharedInstance] syncStopLoading];
    [self.collectionView.mj_footer endRefreshing];
    [self.collectionView.mj_header endRefreshing];
    [UIView performWithoutAnimation:^{
        [self.collectionView reloadData];
    }];
}
#pragma mark ————— collection代理方法 —————
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _logic.dataArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PrivatePhotosCollectionViewCell  *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([PrivatePhotosCollectionViewCell class]) forIndexPath:indexPath];
    cell.backgroundColor = KGrayColor;
    cell.model = _logic.dataArray[indexPath.row];
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if([_touid isEqualToString:curUser.id])
    {
        QMUIAlertController *alertMore = [[QMUIAlertController alloc] initWithTitle:ASLocalizedString(@"操作")message:@"" preferredStyle:QMUIAlertControllerStyleActionSheet];
        [alertMore addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"查看")style:QMUIAlertActionStyleDefault handler:^(QMUIAlertAction *action) {
            NSMutableArray *imageUrls = [NSMutableArray array];
            for (PrivatePhotosModel *model in self->_logic.dataArray) {
                [imageUrls addObject:[OmHandyMethods resizedImageUrlwith:model.img width:@(WINDOW_WIDTH * 2) height:nil]];
            }
            UIImageView *imageView = [[UIImageView alloc] init].fp_contentMode(UIViewContentModeScaleAspectFit);
            [imageView sd_setImageWithURL:[NSURL URLWithString:imageUrls[indexPath.item]]];
            [HUPhotoBrowser showFromImageView:imageView withURLStrings:imageUrls atIndex:indexPath.item];
        }]];
        [alertMore addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"删除")style:QMUIAlertActionStyleDestructive handler:^(QMUIAlertAction *action) {
            NSString *buyTip = [NSString stringWithFormat:ASLocalizedString(@"确定删除此照片？")];
            QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:ASLocalizedString(@"提示")message:buyTip preferredStyle:QMUIAlertControllerStyleAlert];
            [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"取消")style:QMUIAlertActionStyleCancel handler:^(QMUIAlertAction *action) {
            }]];
            [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"确定")style:QMUIAlertActionStyleDestructive handler:^(QMUIAlertAction *action) {
                PrivatePhotosModel *model = _logic.dataArray[indexPath.row];
                [self delPhotoWithId:StringFromInt(model.id)];
            }]];
            [alert showWithAnimated:YES];
        }]];
        [alertMore addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"取消")style:QMUIAlertActionStyleCancel handler:^(QMUIAlertAction *action) {
        }]];
        [alertMore showWithAnimated:YES];
        return;
    }
    NSMutableArray *imageUrls = [NSMutableArray array];
    for (PrivatePhotosModel *model in self->_logic.dataArray) {
        [imageUrls addObject:[OmHandyMethods resizedImageUrlwith:model.img width:@(WINDOW_WIDTH * 2) height:nil]];
    }
    UIImageView *imageView = [[UIImageView alloc] init].fp_contentMode(UIViewContentModeScaleAspectFit);
    [imageView sd_setImageWithURL:[NSURL URLWithString:imageUrls[indexPath.item]]];
    [HUPhotoBrowser showFromImageView:imageView withURLStrings:imageUrls atIndex:indexPath.item];
}
- (void)delPhotoWithId:(NSString *)pid {
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"private_photo_api" A:@"del_photo"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:SafeStr(pid) forKey:@"pid"];
    [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {
    } success:^(id responseObject) {
        [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"删除成功")];
        [_logic loadData];
    } failure:^(NSString *error) {
    } hasCache:NO];
}
-(void)watchMyPhotoWithIndex:(NSIndexPath *)index andCell:(PrivatePhotosCollectionViewCell *)cell
{
    PrivatePhotosModel *model = _logic.dataArray[index.row];
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"private_photo_api" A:@"select_photo"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [[HUDHelper sharedInstance] syncLoading];
    [param setObject:StringFromInt(model.id) forKey:@"pid"];
    [[HUDHelper sharedInstance] syncLoading];
    [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {
    } success:^(id responseObject) {
        [[HUDHelper sharedInstance] syncStopLoading];
        PrivatePhotosCollectionViewCell  *cell = (PrivatePhotosCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:index];
        NSString *img = [responseObject valueForKey:@"img"];
        [ZKPhotoBrowser showWithImageUrls:@[img] currentPhotoIndex:0 sourceSuperView:cell];
    } failure:^(NSString *error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [self buyVideoViewWithModel:model];
    } hasCache:NO];
}
-(void)buyVideoViewWithModel:(PrivatePhotosModel *)model
{
    NSString *buyTip = [NSString stringWithFormat:ASLocalizedString(@"购买图片，需要消耗%@%@，是否购买"),KGlobalVariable.appmodel.private_photos,KCOIN_NAME];
    QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:ASLocalizedString(@"提示")message:buyTip preferredStyle:QMUIAlertControllerStyleAlert];
    [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"取消")style:QMUIAlertActionStyleCancel handler:^(QMUIAlertAction *action) {
    }]];
    [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"购买")style:QMUIAlertActionStyleDefault handler:^(QMUIAlertAction *action) {
        NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"private_photo_api" A:@"pay_personal"];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [[HUDHelper sharedInstance] syncLoading];
        [param setObject:StringFromInt(model.id) forKey:@"pid"];
        [param setObject:SafeStr(curUser.id) forKey:@"uid"];
        [[HUDHelper sharedInstance] syncLoading];
        [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {
        } success:^(id responseObject) {
            [MBProgressHUD showTopTipMessage:ASLocalizedString(@"支付成功!")];
            [[HUDHelper sharedInstance] syncStopLoading];
            [self.collectionView reloadData];
        } failure:^(NSString *error) {
            [[HUDHelper sharedInstance] syncStopLoading];
        } hasCache:NO];
    }]];
    [alert showWithAnimated:YES];
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section == 0 )
    {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (CGSize)collectionView:(nonnull UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    int width = KScreenWidth/3-2;
    return CGSizeMake(width,width);
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    self.collectionView.frame = CGRectMake(0, 0, KScreenWidth, SCREEN_HEIGHT - kTopHeight);
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
